package interceptor;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.zffc.common.util.TraceIdUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * traceId拦截器
 */
@Slf4j
@Component
public class TraceIdInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                           @NonNull Object handler, ModelAndView modelAndView) {
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) {
        String traceId = request.getHeader(TraceIdUtils.TRACE_ID);
        if(Objects.isNull(traceId)){
            traceId = TraceIdUtils.getTraceId();
        }
        TraceIdUtils.setTraceId(traceId);
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest arg0,
                                @NonNull HttpServletResponse arg1,
                                @NonNull Object arg2, Exception arg3) {
        // 删除
        MDC.remove(TraceIdUtils.TRACE_ID);
    }
}
